import { formatDate } from 'share/common';
import { ShoppingService } from 'admin/services/shopping';
import { PromotionRangeComponent } from 'admin/modules/shopping/promotion/activityEdit'
import { coupon as dsCoupon } from 'admin/services/dataSource';
import 'jquery-ui';
import { VirtualMobile, VirtualMobileContext, MobileContextArgument } from 'components/virtualMobile';
import { CouponControl } from 'user/modules/shopping/storeCoupons';
import { app as userApp } from 'user/application';
import React = require('react');
import ReactDOM = require('react-dom');
import * as chitu from "maishu-chitu";
import site from 'admin/site';

export default async function (page: chitu.Page) {

    let app = page.app as chitu.Application;
    let shopping = page.createService(ShoppingService);

    interface CouponEditPageState {
        coupon: Coupon,
    }

    interface CouponEditPageProps extends React.Props<CouponEditPage> {
        coupon: Coupon
    }

    class CouponEditPage extends React.Component<CouponEditPageProps, CouponEditPageState>{
        private validator: dilu.FormValidator;
        private formElement: HTMLElement;
        private productTable: HTMLTableElement;
        private categoryTable: HTMLTableElement;
        private brandTable: HTMLTableElement;

        private titleInput: HTMLInputElement;
        private discountInput: HTMLInputElement;
        private amountInput: HTMLInputElement;

        private validBeginInput: HTMLInputElement;
        private validEndInput: HTMLInputElement;

        constructor(props) {
            super(props);
            this.state = { coupon: {} as Coupon }
            site.loadCSS(page.name);
        }
        setState(value) {
            super.setState(value);
        }
        async save(): Promise<any> {
            if (!await this.validator.check()) {
                return Promise.reject({});
            }

            let { coupon } = this.state;
            coupon.ValidBegin = new Date(this.validBeginInput.value);
            coupon.ValidEnd = new Date(this.validEndInput.value);

            delete coupon['ReceiveBegin'];
            delete coupon['ReceiveEnd'];

            if (coupon.Id)
                return dsCoupon.update(coupon);

            return dsCoupon.insert(coupon);
        }
        private get coupon() {
            let { coupon } = this.state;
            return coupon;
        }
        private set coupon(value: Coupon) {
            // this.state.coupon = value;
            this.setState({ coupon: value })
        }
        async componentDidMount() {
            let { required } = dilu.rules;
            this.validator = new dilu.FormValidator(this.formElement,
                { name: "title", rules: [required("请输入标题")] },
                { name: "discount", rules: [required("请输入抵扣金额")] },
                { name: "amount", rules: [required("请输入消费金额")] },
                { name: "validBegin", rules: [required("请输入开始日期")] },
                { name: "validEnd", rules: [required("请输入结束日期")] }
            );

            ($('[name="validBegin"],[name="validEnd"]') as any).datepicker({
                dateFormat: 'yy-mm-dd',
                beforeShow: function (inputElem, inst) {
                    setTimeout(function () {
                        $('#ui-datepicker-div').css("z-index", 10000);
                    }, 100);
                },
                onSelect: (dateText: string, inst: any) => {
                    let inputElem = inst.input[0];
                    if (inputElem == this.validBeginInput) {
                        this.coupon.ValidBegin = new Date(this.validBeginInput.value);
                        this.setState(this.state);
                    }
                    else if (inputElem == this.validEndInput) {
                        this.coupon.ValidEnd = new Date(this.validEndInput.value);
                        this.setState(this.state);
                    }
                }
            });
            if (page.data.id) {
                let shopping = page.createService(ShoppingService);
                let coupon = await shopping.coupon(page.data.id);
                this.coupon = coupon;
                this.setState(this.state);
                //
                userApp().loadPageLess('shopping_storeCoupons');

            }
        }
        render() {
            let { coupon } = this;
            coupon = coupon || {} as Coupon;
            return <div>
                <div style={{ position: 'absolute' }}>
                    <VirtualMobile>
                        <VirtualMobileContext.Consumer>
                            {(context: MobileContextArgument) => {
                                context.app.loadPageLess('shopping_storeCoupons')
                                return <CouponControl {...{ coupon, page: context.page }} />
                            }}
                        </VirtualMobileContext.Consumer>
                    </VirtualMobile>
                </div>

                <div style={{ paddingLeft: 390 }}
                    ref={(e: HTMLElement) => this.formElement = e || this.formElement} >
                    <ul style={{ margin: 0 }}>
                        <li className="pull-right">
                            <button className="btn btn-sm btn-primary" onClick={() => app.back()}>
                                <i className="icon-reply" />
                                <span>返回</span>
                            </button>
                        </li>
                        <li className="pull-right">
                            <button className="btn btn-sm btn-primary"
                                ref={(e: HTMLButtonElement) => e != null ? ui.buttonOnClick(e, () => this.save(), { toast: '保存页面成功' }) : null}>
                                <i className="icon-save" />
                                <span>保存</span>
                            </button>
                        </li>
                        <li className="clearfix">
                        </li>
                    </ul>
                    <hr style={{ margin: '0 0 15px 0' }} />
                    <div className="row form-group">
                        <div className="col-sm-4">
                            <label className="item-label">标题</label>
                            <div className="item-input">
                                <input name="title" className="form-control"
                                    ref={(e: HTMLInputElement) => this.titleInput = e || this.titleInput}
                                    value={coupon.Title || ''}
                                    onChange={(e) => {
                                        coupon.Title = (e.target as HTMLInputElement).value;
                                        this.setState(this.state);
                                    }} />
                            </div>
                        </div>

                        <div className="col-sm-4">
                            <label className="item-label">抵扣金额</label>
                            <div className="item-input">
                                <input name="discount" className="form-control"
                                    ref={(e: HTMLInputElement) => this.discountInput = e || this.discountInput}
                                    value={coupon.Discount == null ? "" : `${coupon.Discount}`}
                                    onChange={(e) => {
                                        coupon.Discount = Number.parseFloat((e.target as HTMLInputElement).value);
                                        this.setState(this.state);
                                    }} />
                            </div>
                        </div>

                        <div className="col-sm-4 form-group">
                            <label className="item-label">消费金额</label>
                            <div className="item-input">
                                <input name="amount" className="form-control"
                                    ref={(e: HTMLInputElement) => this.amountInput = e || this.amountInput}
                                    value={coupon.Amount == null ? "" : `${coupon.Amount}`}
                                    onChange={(e) => {
                                        var value = Number.parseFloat((e.target as HTMLInputElement).value);
                                        coupon.Amount = isNaN(value) ? null : value;
                                        this.setState(this.state);
                                    }} />
                            </div>
                        </div>
                    </div>
                    <div className="row form-group">
                        <div className="col-sm-4">
                            <label className="item-label">有效日期</label>
                            <div className="item-input">
                                <div className="col-sm-6" style={{ paddingLeft: 0, paddingRight: 0 }}>
                                    <input name="validBegin" className="form-control" placeholder="优惠券使用的开始日期"
                                        ref={(o: HTMLInputElement) => this.validBeginInput = o || this.validBeginInput}
                                        value={coupon.ValidBegin ? formatDate(coupon.ValidBegin) : ""}
                                        onChange={(e) => {
                                            coupon.ValidBegin = new Date((e.target as HTMLInputElement).value);
                                            debugger;
                                            this.setState(this.state);
                                        }} />
                                </div>
                                <div className="col-sm-6" style={{ paddingRight: 0 }}>
                                    <input name="validEnd" className="form-control" placeholder="优惠券使用的结束日期"
                                        ref={(o: HTMLInputElement) => this.validEndInput = o || this.validEndInput}
                                        value={coupon.ValidEnd ? formatDate(coupon.ValidEnd) : ""}
                                        onChange={(e) => {
                                            coupon.ValidEnd = new Date((e.target as HTMLInputElement).value);
                                            this.setState(this.state);
                                        }} />
                                </div>
                            </div>
                        </div>
                        <div className="col-sm-8">
                            <label className="item-label">描述内容</label>
                            <div className="item-input">
                                <input className="form-control" />
                            </div>
                        </div>
                    </div>
                    <hr />
                    <PromotionRangeComponent page={page} rules={coupon.Ranges} />
                </div>
            </div>
        }
    }

    let couponEditPage: CouponEditPage;
    let coupon: Coupon;
    if (page.data.id)
        coupon = await shopping.coupon(page.data.id);

    ReactDOM.render(<CouponEditPage coupon={coupon} ref={(e) => couponEditPage = e} />, page.element);

    // function updatePageState(sender, args) {
    //     // if (page.data.id) {
    //     shopping.coupon(args.id).then(coupon => {
    //         couponEditPage.state.coupon = coupon;
    //         couponEditPage.setState(couponEditPage.state);
    //     });
    //     // }
    // }

    // updatePageState();
    // page.showing.add((sender, args) => updatePageState(sender, args));
}
